package sanduche.controllers;

import java.util.ArrayList;
import java.util.List;

import models.Mensaje;
import models.Recipient;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Http.Session;
import sanduche.play.shared.ModuleConfig;
import sanduche.play.shared.RequestBody;
import sanduche.play.shared.RequestMethod;
import sanduche.play.shared.Route;
import sanduche.play.shared.UrlParam;
import services.DAO;
import services.NotificationsSrv;
import util.SessionObj;

@ModuleConfig(prefix = "/api/mensajeria")
public class MensajeriaController {

	private static SessionObj getSessionObj(Session session) {
		return Json.fromJson(
				Json.parse(session.get(UserController.SESSION_OBJ)),
				SessionObj.class);
	}

	@Transactional
	@Route(value = "/send", method = RequestMethod.POST)
	public static Mensaje sendMessage(@RequestBody Mensaje m, Session session) {

		System.out.println(m.getRecipients());
		for (Recipient r : m.getRecipients()) {
			r.setMensaje(m);
		}
		m.setFechaExacta(System.currentTimeMillis());
		m.setIdSender(getSessionObj(session).getId());
		DAO.persist(m);
		DAO.flush();
		NotificationsSrv.Channel[] recps = new NotificationsSrv.Channel[m
				.getRecipients().size()];
		List<Recipient> recipients = new ArrayList<Recipient>(m.getRecipients());
		for (int i = 0; i < recps.length; i++) {
			recps[i] = recipients.get(i).toChannel();
		}
		NotificationsSrv
				.notify(new NotificationsSrv.MensajeD(m.getId(), m.getMensaje()),
						recps);
		return m;
	}

	@Transactional
	@Route(value = "/alskdj", method = RequestMethod.GET)
	public static Mensaje otraCosa(@RequestBody Mensaje m,
			@UrlParam("idColegio") Long idColegio) {

		return null;
	}

}
